/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.common.util.control;

import java.io.Serializable;
import java.util.LinkedList;

/**
 * 
 * <请简单说明此类用途>
 * 
 * @Title com.enfry.util.control.Eventee
 * @author Penghu
 * @date 2018年1月10日
 */
public class Queue<E> implements Serializable {
	private static final long serialVersionUID = 1L;

	private Lock lock = new Lock();
	private LinkedList<E> list = new LinkedList<E>();

	/** 投递对象 */
	public void post(E e) {
		if (e == null)
			return;

		synchronized (list) {
			list.add(e);
		}

		lock.notifyWait();
	}

	/** 投递对象到消息队列的头部 */
	public void postHead(E e) {
		if (e == null)
			return;

		synchronized (list) {
			list.addFirst(e);
		}

		lock.notifyWait();
	}

	/**
	 * 接收消息队列中的对象，如果当前没有则阻塞线程等待指定时间， 如果等待时间内有通知则读取，等待结束再尝试一次，未读到返回NULL
	 * 
	 * @param timeout 等待时间，以毫秒为单位
	 * @return 如果有消息，则返回消息，如果没有则返回null
	 */
	public E accept(int timeout) {
		synchronized (list) {
			if (!list.isEmpty())
				return list.removeFirst();
		}

		lock.waitNotify(timeout);

		synchronized (list) {
			if (list.isEmpty())
				return null;
			return list.removeFirst();
		}
	}

	/** 对象是否存在对列中 */
	public boolean contains(E e) {
		return list.contains(e);
	}

	/** 当前对列是否为空 */
	public boolean isEmpty() {
		return list.isEmpty();
	}

	/** 获取当前队列长度 */
	public int size() {
		return list.size();
	}

	/** 清除队列消息 */
	public void clear() {
		synchronized (list) {
			list.clear();
		}
	}
}